<?php

namespace common\jobs;

use Yii;
use yii\console\Exception;
use common\helpers\ArrayHelper;
use common\models\ofc\OfcMatch;
use common\models\ofc\OfcTeam;
use common\models\ofc\OfcSeasonTeam;

/**
 * 评论之后执行队列任务
 * Class AfterMatchJob.
 */
class UpdateScheduleJob extends BaseRetryableJob {

    public $season_id = 0;
    public $teams = [];
    public $matchs = [];

    /**
     * @param \yii\queue\Queue $queue which pushed and is handling the job
     */
    public function execute($queue) {
        if (!$this->season_id || empty($this->teams) || empty($this->matchs)) {
            throw new Exception('UpdateScheduleJob need params...');
        }
        $teamData = ArrayHelper::index($this->teams, 'id');
        $teams = OfcTeam::find()->andWhere(['channel_id' => array_keys($teamData)])->all();
        $teamList = ArrayHelper::map($teams, 'channel_id', 'id');
        foreach ($teamData as $ctid => $team) {
            if (isset($teamList[$ctid])) {
                continue;
            }
            $teamid = $this->updateTeam($team);
            if ($teamid) {
                $teamList[$ctid] = $teamid;
            }
        }
        Yii::error([
            $teamList,
            $teamData,
        ], __CLASS__);
        if (count($teamList) != count($teamData)) {
            Yii::error([
                $teamList,
                $teamData,
            ], __CLASS__);
            throw new Exception('球队信息不完整，请刷新球队:' . count($teamList) . ' != ' . count($teamData));
        }

        $matchs = $this->matchs;
        foreach ($matchs as $item) {
            $match = OfcMatch::findOrNew([
                'channel_id' => ArrayHelper::getValue($item, 'id'),
            ]);
            $chostid = ArrayHelper::getValue($item, 'home_team_id');
            $cguestid = ArrayHelper::getValue($item, 'away_team_id');

            $match->attributes = [
                'host_team_id' => ArrayHelper::getValue($teamList, $chostid, 0),
                'guest_team_id' => ArrayHelper::getValue($teamList, $cguestid, 0),
                'host_score' => ArrayHelper::getValue($item, 'home_scores.0', 0),
                'guest_score' => ArrayHelper::getValue($item, 'away_scores.0', 0),
                'match_time' => ArrayHelper::getValue($item, 'match_time', 0),
                'season_id' => $this->season_id,
                'group_id' => ArrayHelper::getValue($item, 'round.group_num', 0),
                'round_id' => ArrayHelper::getValue($item, 'round.round_num', 0),
                'match_status' => ArrayHelper::getValue($item, 'status_id', 0),
            ];
            if (!$match->save()) {
                Yii::error($match->errors, __CLASS__);
            }
        }
    }

    public function updateTeam($data) {
        $team = OfcTeam::findOrNew([
            'channel_id' => ArrayHelper::getValue($data, 'id'),
        ]);
        $logo = ArrayHelper::getValue($data, 'logo');
        $team->attributes = [
            'name' => ArrayHelper::getValue($data, 'name_zh'),
            'name_en' => ArrayHelper::getValue($data, 'name_en'),
            'logo' => $logo ? '/attachments/ofc/team/' . $logo : '',
        ];
        if ($team->isNewRecord) {
            $team->abbr = ArrayHelper::getValue($data, 'name_zh');
            $team->on($team::EVENT_AFTER_INSERT, [$team, 'updateTeam']);
        } else {
            $team->on($team::EVENT_AFTER_UPDATE, [$team, 'updateTeam']);
        }
        if ($team->save()) {
            $teamid = $team->id;
            $seasonteam = OfcSeasonTeam::findOrNew([
                'season_id' => $this->season_id,
                'team_id' => $teamid,
            ]);
            $seasonteam->save();
            return $team->id;
        } else {
            Yii::error($team->errors, __METHOD__);
        }
        return false;
    }

}
